import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:jtlf/message/chat_detail.dart';
import 'package:jtlf/message/notice_detail.dart';

class MessageListPage extends StatefulWidget {
  @override
  _MessageListPageState createState() => _MessageListPageState();
}

class _MessageListPageState extends State<MessageListPage> {
  final List<DingMessage> _messages = [
    DingMessage(
      type: MessageType.group,
      title: 'Flutter项目组',
      content: '@你 请查看最新迭代需求',
      time: '09:30',
      unread: 3,
      avatar: 'https://example.com/group_avatar.png',
      isTop: true,
      status: MessageStatus.unread,
    ),
    DingMessage(
      type: MessageType.private,
      title: '张经理',
      content: '会议纪要已上传至钉盘',
      time: '昨天',
      unread: 0,
      avatar: 'https://example.com/user_avatar.png',
      isTop: false,
      status: MessageStatus.read,
    ),
    // 更多消息项...
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(), // 顶部菜单，2025-3-15 先去掉
      body: _buildMessageList(),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Color(0xFF0089FF),
        child: Icon(Icons.edit),
        onPressed: () {},
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      // title: const Text('消息', textAlign: TextAlign.end), // textAlign为什么没有用？
      title: const Text('消息'), // 其他默认都是居中，这里为什么靠左？下面actions有2个按钮，就靠左了。
      actions: [
        IconButton(icon: Icon(Icons.search), onPressed: () {}),
        IconButton(icon: Icon(Icons.more_vert), onPressed: () {}),
      ],
    );
  }

  Widget _buildMessageList() {
    final topMessages = _messages.where((m) => m.isTop).toList();
    final normalMessages = _messages.where((m) => !m.isTop).toList();

    return CustomScrollView(
      slivers: [
        _buildSectionList('置顶会话', topMessages),
        _buildSectionList('消息列表', normalMessages),
      ],
    );
  }

  Widget _buildSectionList(String title, List<DingMessage> messages) {
    return SliverList(
      delegate: SliverChildListDelegate([
        if (messages.isNotEmpty) _buildSectionHeader(title),
        ...messages.map((msg) => _buildMessageItem(msg)),
      ]),
    );
  }

  Widget _buildSectionHeader(String title) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Text(
        title,
        style: TextStyle(
          color: Colors.grey[600],
          fontSize: 14,
        ),
      ),
    );
  }

  Widget _buildMessageItem(DingMessage msg) {
    return Dismissible(
      key: Key(msg.title),
      background: Container(color: Colors.red),
      secondaryBackground: Container(color: Colors.blue),
      onDismissed: (direction) => _handleDismiss(msg),
      child: InkWell(
        onTap: () => _openChat(msg),
        child: Container(
          color: Colors.white,
          padding: EdgeInsets.symmetric(vertical: 12, horizontal: 16),
          child: Row(
            children: [
              _buildAvatar(msg),
              SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildTitleRow(msg),
                    SizedBox(height: 4),
                    _buildContentRow(msg),
                  ],
                ),
              ),
              _buildRightStatus(msg),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildAvatar(DingMessage msg) {
    return Stack(
      children: [
        CircleAvatar(
          radius: 24,
          backgroundImage: CachedNetworkImageProvider(msg.avatar),
          child: msg.type == MessageType.group
              ? Icon(Icons.group, color: Colors.white)
              : null,
        ),
        if (msg.status == MessageStatus.unread)
          Positioned(
            right: 0,
            child: Container(
              width: 12,
              height: 12,
              decoration: BoxDecoration(
                color: Colors.red,
                shape: BoxShape.circle,
                border: Border.all(color: Colors.white, width: 2),
              ),
            ),
          ),
      ],
    );
  }

  Widget _buildTitleRow(DingMessage msg) {
    return Row(
      children: [
        Expanded(
          child: Text(
            msg.title,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              color: msg.status == MessageStatus.unread
                  ? Colors.black
                  : Colors.grey[600],
            ),
          ),
        ),
        Text(
          msg.time,
          style: TextStyle(color: Colors.grey, fontSize: 12),
        ),
      ],
    );
  }

  Widget _buildContentRow(DingMessage msg) {
    return Row(
      children: [
        if (msg.type == MessageType.notice)
          Icon(Icons.notifications, color: Colors.orange, size: 16),
        if (msg.type == MessageType.task)
          Icon(Icons.assignment, color: Colors.green, size: 16),
        SizedBox(width: 4),
        Expanded(
          child: Text(
            msg.content,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: msg.status == MessageStatus.unread
                  ? Colors.black87
                  : Colors.grey[600],
            ),
          ),
        ),
        if (msg.unread > 0)
          Container(
            padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
            decoration: BoxDecoration(
              color: Colors.red,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Text(
              msg.unread.toString(),
              style: TextStyle(color: Colors.white, fontSize: 12),
            ),
          ),
      ],
    );
  }

  Widget _buildRightStatus(DingMessage msg) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        if (msg.status == MessageStatus.sent)
          Icon(Icons.done, color: Colors.grey, size: 18),
        if (msg.status == MessageStatus.read)
          Icon(Icons.done_all, color: Colors.blue, size: 18),
        SizedBox(height: 8),
        if (msg.isTop)
          Icon(Icons.push_pin, color: Colors.grey, size: 16),
      ],
    );
  }

  void _handleDismiss(DingMessage msg) {
    setState(() => _messages.remove(msg));
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('已删除 ${msg.title} 会话')),
    );
  }

  void _openChat(DingMessage msg) {
    // 打开聊天页面的逻辑
    Navigator.push(
      context,
      MaterialPageRoute(
        // builder: (context) => ChatDetailPage(),
        builder: (context) => NotificationGroupScreen(),
      ),
    );
  }
}

enum MessageType { group, private, notice, task }

enum MessageStatus { unread, read, sent }

class DingMessage {
  final MessageType type;
  final String title;
  final String content;
  final String time;
  final int unread;
  final String avatar;
  final bool isTop;
  final MessageStatus status;

  DingMessage({
    required this.type,
    required this.title,
    required this.content,
    required this.time,
    required this.unread,
    required this.avatar,
    required this.isTop,
    required this.status,
  });
}
